package com.zgis.monitor.service.impl;

import com.zgis.monitor.config.MonitorConfig;
import com.zgis.monitor.model.ServiceStatus;
import com.zgis.monitor.model.dto.ServiceListDTO;
import com.zgis.monitor.service.MonitorService;
import com.zgis.monitor.util.SshUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * docker容器服务监控
 */
@Service
@Slf4j
public class DockerMonitorService implements MonitorService
{

    private final List<MonitorConfig.ServerConfig> serverConfigs;

    // 通过 MonitorConfig 获取 servers
    public DockerMonitorService(MonitorConfig monitorConfig) {
        this.serverConfigs = monitorConfig.getServers();
    }

    @Override
    public ServiceStatus checkStatus(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        ServiceStatus status = new ServiceStatus();
        status.setServerIp(server.getIp());
        status.setServiceId(service.getId());
        status.setServiceName(service.getName());
        status.setType("DOCKER");
        status.setLastCheckTime(LocalDateTime.now());

        if (service.getContainerName() == null || service.getContainerName().isEmpty())
        {
            status.setRunning(false);
            status.setMessage("容器名称未配置");
            return status;
        }

        try
        {
            // 检查容器状态
            String command = String.format("docker inspect --format '{{.State.Status}}' %s", service.getContainerName());
            String result = SshUtil.executeCommand(
                    server.getIp(), server.getSshPort(),
                    server.getUsername(), server.getPassword(),
                    command
            );

            if (result.contains("ERROR") || result.contains("No such container"))
            {
                status.setRunning(false);
                status.setMessage(result);
                return status;
            }

            // 获取容器ID
            String idCommand = String.format("docker inspect --format '{{.Id}}' %s", service.getContainerName());
            String containerId = SshUtil.executeCommand(
                    server.getIp(), server.getSshPort(),
                    server.getUsername(), server.getPassword(),
                    idCommand
            );

            if ("running".equals(result))
            {
                status.setRunning(true);
                status.setPid(containerId.substring(0, 12)); // 取前12位作为容器ID简写
                status.setMessage("容器运行中");
            }
            else
            {
                status.setRunning(false);
                status.setPid(containerId.isEmpty() ? null : containerId.substring(0, 12));
                status.setMessage("容器状态: " + result);
            }
        }
        catch (Exception e)
        {
            status.setRunning(false);
            status.setMessage("检查失败: " + e.getMessage());
            log.error("检查Docker服务状态失败", e);
        }

        return status;
    }

    @Override
    public boolean startService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        if (service.getContainerName() == null || service.getContainerName().isEmpty())
        {
            log.error("容器名称未配置: {}", service.getId());
            return false;
        }

        String composePath = service.getComposePath();
        String command = "cd "+composePath+"; docker-compose up -d";
        String result = SshUtil.executeCommand(
                server.getIp(), server.getSshPort(),
                server.getUsername(), server.getPassword(),
                command
        );

        // 检查是否启动成功
        if (result.contains("ERROR"))
        {
            log.error("启动Docker容器失败: {}", result);
            return false;
        }

        try
        {
            Thread.sleep(1000);
            ServiceStatus status = checkStatus(server, service);
            return status.isRunning();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean stopService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        if (service.getContainerName() == null || service.getContainerName().isEmpty())
        {
            log.error("容器名称未配置: {}", service.getId());
            return false;
        }

        String composePath = service.getComposePath();
        String command = "cd "+composePath+"; docker-compose down";
        String result = SshUtil.executeCommand(
                server.getIp(), server.getSshPort(),
                server.getUsername(), server.getPassword(),
                command
        );

        if (result.contains("ERROR"))
        {
            log.error("停止Docker容器失败: {}", result);
            return false;
        }

        try
        {
            Thread.sleep(1000);
            ServiceStatus status = checkStatus(server, service);
            return !status.isRunning();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean restartService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        return MonitorService.super.restartService(server, service);
    }

    @Override
    public List<ServiceStatus> getAllServiceStatus()
    {
        return null; // 由CompositeMonitorService统一实现
    }

    /**
     * 获取所有服务列表，包含基本信息和状态
     */
    public List<ServiceListDTO> getServiceListWithStatus()
    {
        return Collections.emptyList();
    }
}
    